package work.yj1211.live.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import work.yj1211.live.mapper.RoomMapper;
import work.yj1211.live.mapper.UserMapper;
import work.yj1211.live.utils.Global;
import work.yj1211.live.utils.HttpUtil;
import work.yj1211.live.utils.platForms.Bilibili;
import work.yj1211.live.utils.platForms.CC;
import work.yj1211.live.utils.platForms.Douyu;
import work.yj1211.live.utils.platForms.Huya;
import work.yj1211.live.vo.LiveRoomInfo;
import work.yj1211.live.vo.Owner;
import work.yj1211.live.vo.SimpleRoomInfo;
import work.yj1211.live.vo.platformArea.AreaInfo;

import java.io.*;
import java.util.*;

@Service
public class LiveRoomService {

    @Autowired
    private RoomMapper roomMapper;

    /**
     * 获取总推荐
     * @param page
     * @param size
     * @return
     */
    public List<LiveRoomInfo> getRecommend(int page, int size){
        List<LiveRoomInfo> list = Collections.synchronizedList(new ArrayList<>());
        class MyThread implements Runnable {
            private String platform;
            private List<LiveRoomInfo> list;
            public MyThread(String platform, List<LiveRoomInfo> list){
                this.platform = platform;
                this.list = list;
            }
            @Override
            public void run() {
                list.addAll(getRecommendByPlatform(platform, page, size));
            }
        }

        Thread t1 = new Thread(new MyThread("bilibili", list));
        Thread t2 = new Thread(new MyThread("douyu", list));
        Thread t3 = new Thread(new MyThread("huya", list));
        Thread t4 = new Thread(new MyThread("cc", list));
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        try{
            t1.join();
            t2.join();
            t3.join();
            t4.join();
        }catch (Exception e){
            e.printStackTrace();
        }
//        list.addAll(getRecommendByPlatform("bilibili", page, size));
//        list.addAll(getRecommendByPlatform("douyu", page, size));
//        list.addAll(getRecommendByPlatform("huya", page, size));
//        list.addAll(getRecommendByPlatform("cc", page, size));
        return list;
    }

    /**
     * 根据平台获取总推荐房间列表
     * @param platform
     * @param page
     * @param size
     * @return
     */
    public List<LiveRoomInfo> getRecommendByPlatform(String platform, int page, int size){
        List<LiveRoomInfo> list = null;
        if ("bilibili".equals(platform)){
            list = Bilibili.getRecommend(page, size);
        }
        if("douyu".equals(platform)){
            list = Douyu.getRecommend(page, size);
        }
        if("huya".equals(platform)){
            list = Huya.getRecommend(page, size);//传的不是20的话，得改代码
        }
        if("cc".equals(platform)){
            list = CC.getRecommend(page, size);
        }
        return list;
    }

    /**
     * 根据平台和分区获取推荐房间列表
     * @param platform
     * @param area
     * @param page
     * @param size
     * @return
     */
    public List<LiveRoomInfo> getRecommendByPlatformArea(String platform, String area, int page, int size){
        List<LiveRoomInfo> list = null;
        if ("bilibili".equals(platform)){
            list = Bilibili.getAreaRoom(area, page, size);
        }
        if("douyu".equals(platform)){
            list = Douyu.getAreaRoom(area, page, size);
        }
        if("huya".equals(platform)){
            list = Huya.getAreaRoom(area, page, size);
        }
        if("cc".equals(platform)){
            list = CC.getAreaRoom(area, page, size);
        }
        return list;
    }

    /**
     * 获取真实直播地址
     * @param platForm
     * @param roomId
     * @return
     */
    public Map<String, String> getRealUrl(String platForm, String roomId){
        Map<String, String> urls = new HashMap<>();
        if ("bilibili".equals(platForm)){
            Bilibili.get_real_url(urls, roomId);
        }
        if ("douyu".equals(platForm)){
            Douyu.get_real_url(urls, roomId);
        }
        if ("huya".equals(platForm)){
            Huya.getRealUrl(urls,roomId);
        }
        if ("cc".equals(platForm)){
            CC.getRealUrl(urls,roomId);
        }
        return urls;
    };

    /**
     * 获取用户关注的所有房间信息
     * @param uid     用户uid
     * @return
     */
    public List<LiveRoomInfo> getRoomsByUid(String uid){
        List<LiveRoomInfo> roomList = new ArrayList<>();
        List<SimpleRoomInfo> simpleRoomInfoList = roomMapper.getRoomsByUid(uid);
        LiveRoomInfo liveRoomInfo;
        for(SimpleRoomInfo simpleRoomInfo : simpleRoomInfoList){
            liveRoomInfo = getRoomInfo(uid, simpleRoomInfo.getPlatform(), simpleRoomInfo.getRoomId());
            roomList.add(liveRoomInfo);
        }
        return roomList;
    }

    /**
     * 获取单个直播间信息
     * @param platForm
     * @param roomId
     * @return
     */
    public LiveRoomInfo getRoomInfo(String uid, String platForm, String roomId){
        LiveRoomInfo roomInfo = null;
        if ("bilibili".equals(platForm)){
            roomInfo = Bilibili.get_single_roomInfo(roomId);
        }
        if ("douyu".equals(platForm)){
            roomInfo = Douyu.getRoomInfo(roomId);
        }
        if ("huya".equals(platForm)){
            roomInfo = Huya.getRoomInfo(roomId);
        }
        if ("cc".equals(platForm)){
            roomInfo = CC.getRoomInfo(roomId);
        }
        int isFollowed = roomMapper.ifIsFollowed(uid, platForm,roomId);
        roomInfo.setIsFollowed((isFollowed == 0) ? 0 : 1);
        return roomInfo;
    }

    /**
     * 刷新平台分类的缓存
     * @return
     */
    public void refreshArea(){
        long start = System.currentTimeMillis();
        Douyu.refreshArea();
        Bilibili.refreshArea();
        Huya.refreshArea();
        CC.refreshArea();
        long end = System.currentTimeMillis();
//        log.info("刷新平台分区缓存完成,耗时：" + (end-start) + "毫秒");
    }

    /**
     * 获取指定平台的分区信息
     * @param platform
     * @return
     */
    public List<List<AreaInfo>> getAreaMap(String platform){
        return Global.platformAreaMap.get(platform);
    }

    /**
     * 获取总的分区列表
     * @return
     */
    public List<List<AreaInfo>> getAllAreaMap(){
        List<List<AreaInfo>> result = new ArrayList<>();
        Map<String, Map<String, Map<String, AreaInfo>>> allMap = Global.AllAreaMap;
        List<String> areaTypeSortList = Global.AreaTypeSortList;
        Map<String, List<String>> areaInfoSortMap = Global.AreaInfoSortMap;

        Iterator<String> it = areaTypeSortList.iterator();
        while(it.hasNext()) {
            String areaType = it.next();
            List<String> areaInfoList = areaInfoSortMap.get(areaType);
            Iterator<String> infoIt = areaInfoList.iterator();
            List<AreaInfo> resultList = new ArrayList<>();
            while(infoIt.hasNext()){
                String areaInfo = infoIt.next();
                Map<String, AreaInfo> areaInfoMap = allMap.get(areaType).get(areaInfo);
                if (areaInfoMap.containsKey("douyu")){
                    resultList.add(areaInfoMap.get("douyu"));
                } else if (areaInfoMap.containsKey("bilibili")){
                    resultList.add(areaInfoMap.get("bilibili"));
                } else if (areaInfoMap.containsKey("huya")){
                    resultList.add(areaInfoMap.get("huya"));
                } else if (areaInfoMap.containsKey("cc")){
                    continue;
                }
            }
            if (resultList.size()<1){
                continue;
            }
            result.add(resultList);
        }
        return  result;
    }

    /**
     * 获取分区中所有平台的推荐列表
     * @param area
     * @param page
     * @param size
     * @return
     */
    public List<LiveRoomInfo> getRecommendByAreaAll(String areaType, String area, int page, int size){
        List<LiveRoomInfo> list = new ArrayList<>();
        class MyThread implements Runnable {
            private String platform;
            private List<LiveRoomInfo> list;
            private String area;
            public MyThread(String platform, String area, List<LiveRoomInfo> list){
                this.platform = platform;
                this.list = list;
                this.area = area;
            }
            @Override
            public void run() {
                list.addAll(getRecommendByPlatformArea(platform, area, page, size));
            }
        }
        String areaTypeKey = areaType.substring(0,2);
        Map<String, AreaInfo> map = Global.AllAreaMap.get(areaTypeKey).get(area);
        for (Map.Entry<String, AreaInfo> entry : map.entrySet()) {
            if ("douyu".equals(entry.getKey())){
                Thread t = new Thread(new MyThread("douyu", area, list));
                t.start();
                try {
                    t.join();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if ("bilibili".equals(entry.getKey())){
                Thread t = new Thread(new MyThread("bilibili", area, list));
                t.start();
                try {
                    t.join();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if ("huya".equals(entry.getKey())){
                Thread t = new Thread(new MyThread("huya", area, list));
                t.start();
                try {
                    t.join();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if ("cc".equals(entry.getKey())){
                Thread t = new Thread(new MyThread("cc", area, list));
                t.start();
                try {
                    t.join();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return list;
    }

    /**
     * 搜索
     * @param platform 搜索的目标平台，"all"为搜索所有平台
     * @param keyWords 搜索关键字
     * @param isLive 是否搜索直播中的信息
     * @return
     */
    public List<Owner> search(String platform, String keyWords, String isLive){
        List<Owner> list = new ArrayList<>();
        if ("douyu".equals(platform)){
            List<Owner> douyuList = Douyu.search(keyWords, isLive);
            list.addAll(douyuList);
        }
        if ("bilibili".equals(platform)){
            List<Owner> bilibiliList = Bilibili.search(keyWords, isLive);
            list.addAll(bilibiliList);
        }
        if ("huya".equals(platform)){
            List<Owner> huyaList = Huya.search(keyWords, isLive);
            list.addAll(huyaList);
        }
        if ("cc".equals(platform)){
            List<Owner> ccList = CC.search(keyWords, isLive);
            list.addAll(ccList);
        }
        if ("all".equals(platform)){
            List<Owner> douyuList = Douyu.search(keyWords, isLive);
            List<Owner> bilibiliList = Bilibili.search(keyWords, isLive);
            List<Owner> huyaList = Huya.search(keyWords, isLive);
            List<Owner> ccList = CC.search(keyWords, isLive);
            list.addAll(ccList);
            list.addAll(huyaList);
            list.addAll(bilibiliList);
            list.addAll(douyuList);
        }
        return list;
    }
}
